<script setup lang='ts'>
import { onMounted, ref, reactive, getCurrentInstance, nextTick } from "vue";
import {
  Search,
  Refresh,
  Plus,
  Sort,
  DeleteFilled,
  EditPen,
} from "@element-plus/icons-vue";
import { useDeptStore } from "@/stores/modules/dept";
import { dateFormat } from "@/utils/time";
import type { FormInstance, FormRules } from "element-plus";
import { transTree } from "@/utils/recorison";
import { ElMessage, ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();

const deptStore = useDeptStore();

let deptList = ref([]);
const getList = async () => {
  await deptStore.getList();
  deptList.value = JSON.parse(JSON.stringify(transTree(deptStore.list, 0)));
};

onMounted(async () => {
  await getList();
});
// 显示新增表单
const dialogVisible = ref(false);
const showDialog = (row: any) => {
  dialogVisible.value = !dialogVisible.value;
  if (row) {
    Object.assign(formData, { pid: row.id });
  }
};

// 表单信息
const formData = reactive({
  name: "",
  pid: "",
  deptName: "",
  userName: "",
  Mobile: "",
  email: "",
  status: 1,
  sort: "",
});

// 表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  pid: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
  deptName: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "显示排序不能为空", trigger: "change" }],
});

// 修改
let editId = ref();
const editData = async (row: any) => {
  dialogVisible.value = !dialogVisible.value;
  if (row.pid == 0) {
    Object.assign(formData, { ...row, pid: 1 });
  } else {
    Object.assign(formData, row);
  }
  editId.value = row.id;
  deptList.value = deptStore.list;
  await deptStore.getList();
  deptList.value = JSON.parse(JSON.stringify(transTree(deptStore.list, 0)));
};

// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (editId.value) {
        if (editId.value == 1) {
          formData.pid = 0;
        }
        await deptStore.postSave(Object.assign(formData, { id: editId.value }));
      } else {
        await deptStore.postSave(formData);
      }
      await getList();
      dialogVisible.value = !dialogVisible.value;
      editId.value = null;
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 清空表单
const reset = () => {
  // dialogVisible.value = false;
  Object.assign(formData, {
    //清空表单
    name: "",
    pid: "",
    deptName: "",
    userName: "",
    Mobile: "",
    email: "",
    status: 1,
    sort: "",
  });
};

// 删除
const delData = (row: any) => {
  ElMessageBox.confirm(
    `是否确认删除名称为"${row.deptName}"的数据项？`,
    "系统提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      deptStore.getDelete(row.id);
      await getList();
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    })
    .catch(() => {});
};

// 搜索
const search = async () => {
  await deptStore.getList();
  deptList.value = deptStore.list;
};

// 隐藏搜索
const isShowSearch = ref(true);
const onShowSearch = () => {
  isShowSearch.value = !isShowSearch.value;
};

// 刷新
const loading = ref(false);
const flush = async () => {
  loading.value = true;
  await search();
  setTimeout(() => {
    loading.value = false;
  }, 1000);
};

//重置
const resh = () => {
  loading.value = true;
  deptStore.query1 = "";
  deptStore.query2 = "";
  setTimeout(() => {
    loading.value = false;
  }, 1000);
  getList();
  deptList.value = JSON.parse(JSON.stringify(transTree(deptStore.list, 0)));
};
// 折叠
const refreshTable = ref(true);
const isExpandAll = ref(true);
const fold = () => {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
};

// const hideDialog = ()=>{
//   reset()
// }
</script>

<template>
  <el-form v-if="isShowSearch" :inline="true" class="form-1 demo-form-inline">
    <el-form-item label="部门名称">
      <el-input v-model="deptStore.query1" placeholder="请输入部门名称" />
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model="deptStore.query2" placeholder="用户状态">
        <el-option label="启用" :value="1" />
        <el-option label="停用" :value="0" />
      </el-select>
    </el-form-item>
    <el-form-item label="">
      <el-button type="primary" @click="search" :icon="Search">搜索</el-button>
      <el-button @click="resh" :icon="Refresh">重置</el-button>
    </el-form-item>
  </el-form>
  <div class="buttonGroup">
    <div>
      <el-button type="primary" @click="showDialog(false)" :icon="Plus" plain
        >新增</el-button
      >
      <el-button type="info" @click="fold" :icon="Sort" plain
        >展开/折叠</el-button
      >
    </div>
    <div>
      <el-tooltip placement="top">
        <template #content> {{ isShowSearch ? "隐藏" : "显示" }}搜索</template>
        <el-button @click="onShowSearch" :icon="Search" circle />
      </el-tooltip>
      <el-tooltip placement="top">
        <template #content> 刷新</template>
        <el-button @click="flush" :icon="Refresh" circle />
      </el-tooltip>
    </div>
  </div>
  <!-- 表格 -->
  <el-table
    v-loading="loading"
    :data="deptList"
    v-if="refreshTable"
    :header-cell-style="{ background: '#f8f8f9', color: '#606266' }"
    row-key="id"
    lazy
    :default-expand-all="isExpandAll"
    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    style="width: 100%"
  >
    <el-table-column prop="deptName" label="部门名称" width="180" />
    <el-table-column prop="pid" label="排序" width="180" />
    <el-table-column prop="status" label="状态" width="180">
      <template #default="scope">
        <el-tag v-if="scope.row.status">正常</el-tag>
        <el-tag v-else type="danger">停用</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间">
      <template #default="scope">
        {{ dateFormat(scope.row.createTime) }}
      </template>
    </el-table-column>
    <el-table-column prop="name" label="操作">
      <template #default="scope">
        <div>
          <el-link type="primary" @click="editData(scope.row)" :icon="EditPen"
            >修改</el-link
          >
          <el-link type="primary" @click="showDialog(scope.row)" :icon="Plus"
            >新增</el-link
          >
          <el-link
            type="primary"
            @click="delData(scope.row)"
            v-if="scope.row.id != 1"
            :icon="DeleteFilled"
            >删除</el-link
          >
        </div>
      </template>
    </el-table-column>
  </el-table>
  <!-- 新增表单对话框 -->
  <el-dialog
    @close="reset"
    v-model="dialogVisible"
    title="添加部门"
    width="35%"
  >
    <el-form
      ref="ruleFormRef"
      :rules="rules"
      :model="formData"
      label-width="120px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item class="parentId" label="上级部门" prop="pid">
            <el-tree-select
              v-model="formData.pid"
              :props="{
                value: 'id',
                label: 'deptName',
                children: 'children',
              }"
              placeholder="选择上级部门"
              check-strictly
              :data="deptList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="name" label="部门名称">
            <el-input v-model="formData.deptName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item pror="sort" label="显示排序">
            <el-input-number
              v-model="formData.sort"
              :min="0"
              :max="10"
              controls-position="right"
              size="large"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人">
            <el-input v-model="formData.userName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话">
            <el-input v-model="formData.Mobile" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱">
            <el-input v-model="formData.email" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门状态">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.parentId >>> .el-input__wrapper {
  width: 440px;
}
.el-form >>> .el-form-item__label {
  font-weight: 800;
}
/* .el-table >>> .cell {
  text-align: center;
} */
.el-link {
  margin-right: 10px;
}
.buttonGroup {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.form-1 >>> .el-form-item__label {
  font-weight: 800;
}
</style>